<?php

namespace App\Admin\Controller\Cms;

class Event extends \App\Admin\Controller\Authed {

    public function index() {

        $do = $this->request->get('do');

        if ($do == 'sort') {
            $sorts = $this->request->getPost('sorts');

            foreach ($sorts as $key => $value) {
                $result = Cms()->Event()->setSort($key, $value);

                if (!$result) {
                    fail();
                }
            }

            succ();
        }

        $filter_title = urldecode(trim($this->request->get('filter_title')));
        $filter_begin = trim($this->request->get('filter_begin', ''));
        $filter_end = trim($this->request->get('filter_end', ''));

        if ($filter_title) {
            $filter['title'] = array('like' => "%{$filter_title}%");
        }

        if ($filter_begin && $filter_end) {
            $filter['add_time'] = array('between' => $filter_begin, 'and' => $filter_end . ' 23:59:59');
        }

        $count = Cms()->Event()->countAll($filter);

        /* 分页 */
        $pager = $this->_createPager($count);
        $length = $pager['length'];
        $start = $pager['offset'];
        $this->assign('pager', $pager);

        $rows = Cms()->Event()->getAll($start, $length, $filter);

        foreach ($rows as &$row) {
            $row['state_title'] = Cms()->Event()->getStateAssoc($row['state']);
        }
        
        $this->rows = $rows;
    }

    public function edit() {
        
        $this->enablePageCache(true);

        $id = intval($this->request->get('id'));

        $editor = new \WangEditor4();
        $editor->chunk_upload_server = '/admin/upload/chunk';
        $editor->base64_upload_server = '/admin/upload/base64';
        $editor->remote_capture_server = '/admin/upload/capture';

        if ($this->request->isPost()) {

            $data = $this->request->get();

            $data['content'] = $editor->getContent();

            if (!$data['title']) {
                fail('标题不能为空');
            }

            if ($id) {
                $result = Cms()->Event()->update($id, $data);
                if ($result) {
                    succ('', '', 2);
                } else {
                    fail();
                }
            } else {
                $result = Cms()->Event()->add($data);
                if ($result) {
                    succ('', '', 2);
                } else {
                    fail();
                }
            }
        }

        $this->detail = Cms()->Event()->get($id);

        $editor->setContent($this->detail['content']);

        $this->editor = $editor;

        $this->states = Cms()->Event()->getStateAssoc();
    }

    public function remove() {

        $id = intval($this->request->get('id'));

        $result = Cms()->Event()->remove($id);

        if ($result) {
            succ();
        } else {
            fail();
        }
    }

}
